import React, { useState, useEffect, FC, SyntheticEvent, ChangeEvent, useRef, useContext, forwardRef, useImperativeHandle } from 'react'
import { Space, Col, Row, Table, Modal, Input, Form, InputRef } from 'antd'
import { Scrollbars } from 'react-custom-scrollbars'
import type { FormInstance } from 'antd/es/form'
import XlModalFC from '@/components/xlmodal/xlmodal'
import XlButtonFC from '@/components/xlbutton/xlbutton'
import { DownOutlinedIcon } from '@/models/icons'
import { IData, PagingSize, DictionaryItemsModal, IResponseCodeType } from '@/models/common'
import util from '@/utils/util'
import * as api from '@/api'
import './dictvaluemodal.scss'

interface ColumnsDataType {
  [name: string]: string
}

type EditableTableProps = Parameters<typeof Table>[0]
type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>
interface EditableRowProps {
  index: number;
}
interface EditableCellProps {
  title: React.ReactNode;
  editable: boolean;
  children: React.ReactNode;
  dataIndex: keyof ColumnsDataType;
  record: ColumnsDataType;
  handleSave: (record: ColumnsDataType) => void;
}
const EditableContext = React.createContext<FormInstance<any> | null>(null)
const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
  const [form] = Form.useForm()
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  )
}

const EditableCell: React.FC<EditableCellProps> = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef<InputRef>(null);
  const form = useContext(EditableContext)!;

  useEffect(() => {
    if (editing) {
      inputRef.current!.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({ [dataIndex]: record[dataIndex] });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();

      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{ margin: 0 }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `${title}不能为空`,
          },
        ]}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={toggleEdit}>
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
}
export interface IDictValueRef {
  getValue: (type_id: string) => void
}
export interface IDictValueXlModalProps {
  onCancel?: () => void
  onOk?: () => void
  ref?: React.ForwardedRef<IDictValueRef>
}

export interface IViewModel {
  pageLoading: boolean
  /**
   * 表格数据
   */
  dictTableList: ColumnsDataType[]
  /**
   * 当前页码
   */
  page: number
  /**
   * 每页数量
   */
  pageSize: number
  /**
   * 是否还有下一页
   */
  hasNextPage: boolean
  dictValueModalOpen: boolean
  type_id: string
}

const DictValueXlModal: FC<IDictValueXlModalProps> = forwardRef((props, ref) => {
  const { onCancel, onOk } = props
  const [data, setData] = useState<IData<IViewModel>>({
    ViewModel: {
      pageLoading: false,
      dictValueModalOpen: false,
      dictTableList: [],
      page: 1,
      pageSize: PagingSize.PageSize,
      hasNextPage: false,
      type_id: ''
    }
  })

  useImperativeHandle(ref, () => ({
    getValue: (type_id: string) => {
      methods.requestDictionaryValueList(type_id)
    },
  }))

  const events = {
    onClickAddRow() {
      const { ViewModel } = data
      let dictTableList = ViewModel.dictTableList
      dictTableList.push({
        id: util.getGuid('temp_'),
        label: "",
        order_sort: ""
      })
      ViewModel.dictTableList = [...dictTableList]
      setData({ ...data })
    },
    onClickDeleteRow(_: ColumnsDataType, record: ColumnsDataType, index: number) {
      Modal.confirm({
        title: '删除',
        centered: true,
        closable: true,
        content: '确认删除吗？',
        onOk() {
          return new Promise(async (resolve, reject) => {
            const { ViewModel } = data
            let dictTableList = ViewModel.dictTableList
            dictTableList.splice(index, 1)
            ViewModel.dictTableList = [...dictTableList]
            setData({ ...data })
            resolve(null)
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() {

        },
      })
    },
    onClickLoadMore() {
      const { ViewModel } = data
      if (ViewModel.hasNextPage) {
        // ViewModel.page = ViewModel.page + 1
        // ViewModel.pageLoading = true
        // setData({ ...data })
        // methods.querySubTableList()
      }
    },
    handleSave(row: ColumnsDataType) {
      const { ViewModel } = data
      const newData = [...ViewModel.dictTableList];
      const index = newData.findIndex(item => row.id === item.id);
      const item = newData[index];
      newData.splice(index, 1, {
        ...item,
        ...row,
      });
      ViewModel.dictTableList = [...newData]
      setData({ ...data })
    },
    onDictValueXlModalOk() {
      const { ViewModel } = data
      let flag = true
      if (ViewModel.dictTableList.length) {
        for (let i = 0; i < ViewModel.dictTableList.length; i++) {
          const element = ViewModel.dictTableList[i];
          if (!element.label) {
            flag = false
            break
          }
        }
      }
      if (!flag) {
        util.alertTip('数据字典的值不能为空')
        return
      }
      methods.requestUpdateDictionaryValueList()
    },
    onDictValueXlModalCancel() {
      const { ViewModel } = data
      ViewModel.dictValueModalOpen = false
      setData({ ...data })
    },
  }

  const methods = {
    async requestDictionaryValueList(type_id: string) {
      const { ViewModel } = data
      ViewModel.pageLoading = true
      setData({ ...data })
      let res = await api.common.getDictionaryItems<DictionaryItemsModal>({
        type_id
      })
      const { code, data: dictionaryItemData, message } = res
      if (code == IResponseCodeType.Success) {
        let { item_list } = dictionaryItemData
        ViewModel.dictTableList = [...item_list]
        if (item_list.length < ViewModel.pageSize) {
          ViewModel.hasNextPage = false
        } else {
          ViewModel.hasNextPage = false
        }
      } else {
        util.alertTip(message)
      }
      ViewModel.pageLoading = false
      ViewModel.dictValueModalOpen = true
      ViewModel.type_id = type_id
      setData({ ...data })
    },
    async requestUpdateDictionaryValueList() {
      const { ViewModel } = data
      let res = await api.common.updateDictionaryItem<null>({
        type_id: ViewModel.type_id,
        items_json: JSON.stringify(ViewModel.dictTableList)
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        ViewModel.dictValueModalOpen = false
      } else {
        util.alertTip(message)
      }
      setData({ ...data })
    },
    createColumns() {
      const columns: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[] = [
        {
          title: '值',
          align: "left",
          key: 'label',
          dataIndex: 'label',
          editable: true,
          onCell: (record: any) => ({
            record,
            editable: true,
            dataIndex: 'label',
            title: '值',
            handleSave: events.handleSave,
          }),
        },
        {
          title: '操作',
          align: "center",
          width: 80,
          dataIndex: "action",
          key: 'action',
          render: (_, record: any, index) => (
            <XlButtonFC type='primary' size='small' onClick={() => events.onClickDeleteRow(_, record, index)}>
              删除
            </XlButtonFC>
          ),
        }
      ]
      return columns
    },
    renderPage() {
      return (
        <XlModalFC
          title="设置值"
          open={data.ViewModel.dictValueModalOpen}
          onOk={events.onDictValueXlModalOk}
          onCancel={events.onDictValueXlModalCancel}
          cancelText="取消"
          okText="确定"
          className='dict-value-modal'
          width={600}
        >
          <Col className='dict-setting-wrap'>
            {/* 按钮操作区域 */}
            <Row align='middle' justify='space-between' className='buttonGroupWrap' gutter={[0, 10]}>
              <Col>
                <Space size={6}>
                  <XlButtonFC type='primary' onClick={events.onClickAddRow}>新增</XlButtonFC>
                </Space>
              </Col>
              <Col className='count'>
                {data.ViewModel.hasNextPage ? '已部分加载' : '已全部加载'}，共{data.ViewModel.dictTableList.length}个
              </Col>
            </Row>
            {/* 表格区域 */}
            <Col className='tableWrap'>
              <Col className='tableContent'>
                <Table
                  scroll={{
                    x: '100%',
                    y: 400
                  }}
                  components={{
                    body: {
                      row: EditableRow,
                      cell: EditableCell,
                    }
                  }}
                  rowClassName={() => 'editable-row'}
                  loading={data.ViewModel.pageLoading}
                  tableLayout='fixed'
                  bordered
                  rowKey='id'
                  pagination={false}
                  columns={methods.createColumns()}
                  dataSource={data.ViewModel.dictTableList}
                />
              </Col>

              {
                data.ViewModel.hasNextPage ? <Row className='loadmore-wrap' onClick={events.onClickLoadMore}>
                  <Col>点击加载更多</Col>
                  <Row><DownOutlinedIcon className='loadmore-icon' /></Row>
                </Row> : null
              }
            </Col>
          </Col>
        </XlModalFC>
      )
    }
  }

  return methods.renderPage()

})

export default DictValueXlModal
